﻿using System;
using System.ComponentModel.Composition;
using System.Web;
using Glimpse.Core.Extensibility;
using Glimpse.Elmah.Configuration;
using Glimpse.Elmah.Infrastructure;

namespace Glimpse.Elmah.Plugin
{
	[GlimpsePlugin]
	public class ElmahPlugin : IGlimpsePlugin, IProvideGlimpseHelp
	{
		private readonly IRepository _repository;

        [ImportingConstructor]
		public ElmahPlugin() 
            : this(new ErrorRepository())
		{
		}

		public ElmahPlugin(IRepository repository)
		{
			if (repository == null)
				throw new ArgumentNullException("repository");

			_repository = repository;
		}

		public string Name
		{
			get { return "Elmah"; }
		}

        public string HelpUrl
        {
            get { return "http://elmah4glimpse.codeplex.com/"; }
        }

		public object GetData(HttpContextBase contextBase)
		{
            // Validate parameters
            if (contextBase == null)
                return null;

			// Get the errors
            var errorPage = _repository.GetErrorPage(contextBase, 0, Settings.DefaultPageSize);
			if (errorPage == null)
				return null;

            var data = errorPage.GetData(contextBase);
			return data;
		}

		public void SetupInit()
		{
		}
	}
}